package com.cos.shop.web.filter;

import com.cos.shop.common.Const;
import com.cos.shop.entity.User;
import com.cos.shop.services.UserServices;
import com.cos.shop.services.impl.UserServicesImpl;
import com.cos.shop.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: COS
 * @time: 2022/2/23 17:11
 * @description: 检查处理自动登录的过滤器 ,精确过滤login.jsp,其余不过滤
 */
@WebFilter(filterName = "Filter02_AutoLogin",value = "/login.jsp")
public class Filter02_AutoLogin implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //检查用户是否设置自动登录
        //看看cookie中是否有Const.AUTO_LOGIN的存在
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            //判断是否有自动登录标识的cookie存在
            if (cookie.getName().equals(Const.AUTO_LOGIN)) {
                //再次检查登录 用户名密码
                //1 先在cookie获取到用户名和密码
                //不要忘了解码
                String[] split = Base64Utils.decode(cookie.getValue()).split(":");
                String username = split[0];
                String password = split[1];
                //2 创建userservices对象调用登录业务操作
                UserServices us = new UserServicesImpl();
                User login = us.login(username, password);
                //判断登录是否成功
                if (login != null) {
                    //登录成功
                    //设置用户数据到session当中
                    request.getSession().setAttribute(Const.IS_LOGIN,login);
                    //直接重定向到index.jsp
                    response.sendRedirect(request.getContextPath()+"/index.jsp");
                    //结束不让他继续执行下次
                    return;
                }
            }
        }
        //直接放行
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
